# -*- coding: utf-8 -*-
import json

from selenium.webdriver.chrome.webdriver import WebDriver


class ZhiDaoWebDataObtain:

    http_logs: list

    chrome_driver: WebDriver

    verify_response_code: bool

    def __init__(self, chrome_driver: WebDriver, verify_response_code: bool = True):
        self.chrome_driver = chrome_driver
        self.http_logs = chrome_driver.get_log("performance")
        self.verify_response_code = verify_response_code
        print("网络监控开启")

    # 监控网络请求，获取弹窗问题答案
    def get_data(self,  query_url: str):
        http_response = self.find(query_url)
        if http_response is None:
            new_http_logs = self.chrome_driver.get_log("performance")
            self.http_logs.extend(new_http_logs)
            http_response = self.find(query_url)
        return http_response

    def find(self, query_url: str):
        if self.http_logs is None:
            return None
        for log in self.http_logs:
            if type(log) == list:
                continue
            message = json.loads(log.get("message"))
            if message is None:
                continue
            second_message = message.get("message")
            if second_message is None:
                continue
            request_method = second_message.get('method')
            if request_method is None:
                continue
            if request_method != 'Network.responseReceived':
                continue
            params = second_message.get('params')
            if params is None:
                continue
            if params.get('type') != 'Fetch' and params.get('type') != 'XHR':
                continue
            response = params.get('response')
            if response is None:
                continue
            url = response.get('url')
            if url != query_url:
                continue
            request_id = params.get('requestId')
            if request_id is None:
                continue
            return self.http_response_monitor(request_id)

    def http_response_monitor(self, request_id):
        self.chrome_driver.execute_cdp_cmd('Network.enable', {})
        # 监听网络事件
        response = self.chrome_driver.execute_cdp_cmd(
            'Network.getResponseBody',
            {'requestId': request_id}
        )
        response_body = response.get('body')
        if response_body is None:
            return None
        response_json = json.loads(response_body)
        if not self.verify_response_code:
            return response_json
        code = response_json.get('code')
        if code != 0:
            return None
        return response_json.get('data')
